package jp.co.sapporobeer.FMCOutgoing;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneStateService extends Service {

	private TelephonyManager telephonyManager;
	private CallStateListener callStateListener;
	private boolean cb_disconnect_end_vibrate = false;
	
	@Override
	public IBinder onBind(Intent arg0) {
		Log.i(getClass().getSimpleName(), "onBind()");
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.i(getClass().getSimpleName(), "OnCreate()");

		telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		callStateListener = new CallStateListener();
		telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.i(getClass().getSimpleName(), "OnStart()");		
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.i(getClass().getSimpleName(), "onDestroy()");		
		;
	}
	
	private class CallStateListener extends PhoneStateListener {

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			super.onCallStateChanged(state, incomingNumber);
			Log.i(getClass().getSimpleName(), "onCallStateChanged:" + incomingNumber);

			PhoneStateService.this.onCallStateChanged(state, incomingNumber);
		}
	}
	
	private void onCallStateChanged(int state, String incomingNumber) {

		switch (state) {
		case TelephonyManager.CALL_STATE_IDLE:
			Log.i(getClass().getSimpleName(), "CALL_STATE_IDLE:" + incomingNumber);

			// プリファレンスの呼び出し
			Context context = getApplicationContext();
			SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
			cb_disconnect_end_vibrate = sharedPreferences.getBoolean("key_disconnect_end_vibrate", false);
			
			if (cb_disconnect_end_vibrate){
				((Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(150);
			}
			
			break;

		case TelephonyManager.CALL_STATE_RINGING:
			Log.i(getClass().getSimpleName(), "CALL_STATE_RINGING:" + incomingNumber);
			break;

		case TelephonyManager.CALL_STATE_OFFHOOK:
			Log.i(getClass().getSimpleName(), "CALL_STATE_OFFHOOK:" + incomingNumber);
			
			break;
		}
	}

}
